package com.clf.springBoot.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: chenglongfei
 * @date: 2022/7/5
 * @Description MyAop
 */
@Aspect
@Component
public class MyAop {
    public final static Logger LOGGER= LoggerFactory.getLogger(MyAop.class);


    @Pointcut("execution(public * com.clf.springBoot.modules.*.controller.*.*(..))")
    @Order(1)
    public void controllerPointCut(){}

    @Pointcut("@annotation(com.clf.springBoot.aop.MyAnnotation)")
    @Order(1)
    public void annotationPointCut(){}


    @Before(value = "controllerPointCut()")
    public void beforeControllerPointCut(JoinPoint joinPoint) {
        LOGGER.debug("-------- Before Controller ---------");
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        LOGGER.debug(String.format("请求路径: %s", request.getRequestURL()));
        LOGGER.debug(String.format("请求方式: %s", request.getMethod()));
        LOGGER.debug(String.format("请求类: %s", joinPoint.getTarget().getClass()));
        LOGGER.debug(String.format("请求方法: %s", joinPoint.getSignature().getName()));
    }


    @Around(value = "controllerPointCut()")
    public Object aroundControllerPointCut(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        LOGGER.debug("-------- Around Controller ---------");
        return proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
    }

    @After(value = "controllerPointCut()")
    public void afterControllerPointCut() {
        LOGGER.debug("-------- After Controller ---------");
    }

    @Around(value = "annotationPointCut()")
    public Object aroundAnnotationPointCut(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        LOGGER.debug("-------- Around Annotation ---------");
        long start = System.currentTimeMillis();
        Object rerult = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        long end = System.currentTimeMillis();

        LOGGER.debug(String.format("方法执行时间: %s", (end - start)));

        return rerult;
    }

}
